import fs from "fs";
import path from "path";
import { isDirectory } from "../utils/tools";

// Model文件名（不包括后缀）
const MODULE_FILE_NAME = "Entity";

export const getAllEntity = async () => {
  const entitys: any[] = [];

  const handler = async (originPath: string) => {
    // 得到目录下的所有内容
    let dirs = await fs.promises.readdir(originPath);
    // 过滤掉 template
    dirs = dirs.filter(item => !item.includes("template"))
    
    for (const filename of dirs) {
      // 得到绝对路径
      const target = path.resolve(originPath, filename)

      // 是否为目录
      if (await isDirectory(target)) {
        // 是目录则递归处理
        await handler(target)
      } else if (path.basename(filename, path.extname(filename)) === MODULE_FILE_NAME) {
        // 是Entity文件则导入
        const modelPath = path.resolve(originPath, path.basename(filename, path.extname(filename)))
        const res = await import(modelPath);
        entitys.push(res.default as any);
      }
    }
  }
  await handler(__dirname)

  return entitys;
}
